import React, { Component } from "react";
import { BrowserRouter, Switch, Route, Redirect } from "react-router-dom";
import { routes, whiteList } from "./router/index.js";

export default class App extends Component {
    render() {
        return (
            <div className="app">
                <BrowserRouter>
                    <Switch>
                        {routes.map((route) => {
                            return (
                                <Route
                                    key={route.path}
                                    path={route.path}
                                    render={(props) => {
                                        // 从 sessionStorage 拿用户的状态
                                        const user = window.sessionStorage.getItem(
                                            "user"
                                        );

                                        // location: 能取到路由的路径相关的信息
                                        // match: 能取到路由参数信息
                                        // history: 浏览器 history 对象，可以完成页面的跳转
                                        if (
                                            user ||
                                            whiteList.includes(
                                                props.location.pathname
                                            )
                                        ) {
                                            return (
                                                <route.component {...props} />
                                            );
                                        }

                                        // 直接重定向到登录页面
                                        return <Redirect to="/login" />;
                                    }}
                                />
                            );
                        })}
                    </Switch>
                </BrowserRouter>
            </div>
        );
    }
}
